package com.example.service;

import com.example.DTO.OrderItemDTO;
import com.example.Ordermodule.OrderFactorym;
import com.example.Ordermodule.OrderItemm;
import com.example.Ordermodule.Orderm;
import com.example.entity.Product;
import com.example.entity.StandardItem;
import com.example.entity.StandardOrder;
import com.example.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;

@Service
public class StandardService {
    @Autowired
    private OrderFactorym factory;
    @Resource
    private OrdermDao ordermDao;
    @Resource
    private OrderItemDao orderItemDao;
    @Resource
    private ProductDao productDao;
    @Resource
    private ShoppingCartMapper shoppingCartMapper;
    @Resource
    private BuyerMapper buyerMapper;
    @Resource
    private OrderItemDTOMapper orderItemDTOMapper;


    //创建订单并添加订单项
    public Orderm createOrder(Integer buyerId, Map<Integer,Integer> items,Integer adressId) {
        //先检验库存，感觉将检验方法写在工厂方法中会比较好但是就目前来看先写在这里
        for(Map.Entry<Integer,Integer> entry : items.entrySet()) {
            Integer productId = entry.getKey();
            Integer quantity = entry.getValue();

            Product product = productDao.queryById(productId);
            if(product == null) {
                throw new RuntimeException("商品ID"+productId+"不存在");
            }
            if(product.getStock() < quantity) {
                throw new RuntimeException("商品ID"+productId+"库存不足，当前库存:"+product.getStock());
            }
        }
        //使用工厂创建订单
        StandardOrder order =(StandardOrder) this.factory.createOrder(buyerId);

        //遍历所有商品并创建每个商品
        items.forEach((productId, quantity)->{
            OrderItemm item=this.factory.createItem(productId, quantity);
            order.addItem(item);
        });
        order.calculateTotalPrice();
        //验证订单
        order.validate();
        //扣减库存,考虑到可能是从购物车中购买的商品需要重购物车当中删除相关内容,在此依据buyerid与productid来进行
        for(Map.Entry<Integer,Integer> entry : items.entrySet()) {
            Integer productId = entry.getKey();
            Integer quantity = entry.getValue();
            productDao.decreaseStock(productId,quantity);
            shoppingCartMapper.deleteShopcart(buyerId,productId);
        }
        /*以下程序很不好之后改进*/
        // 保存订单到数据库
        ordermDao.insertOrder(order);
        // 保存订单项到数据库
        order.getItems().forEach(item -> {
            // 将 item 强制转换为 StandardItem 类型
            StandardItem standardItem = (StandardItem) item;
            // 设置订单ID
            standardItem.setOrderId(order.getOrderId());
            //设置订单项的地址Id
            standardItem.setAddressId(adressId);
            // 保存订单项
            orderItemDao.insertOrderItem(standardItem);
        });

        //返回订单对象
        return order;

    }
    //删除订单或者删除部分订单项，这个写得太差了吧这么多for循环之后改进
    @Transactional
    public boolean deleteOrder(Integer orderId, List<Integer> productIds) {
        //查找订单
        StandardOrder order=ordermDao.queryById(orderId);
        if(order==null){
            return false;
        }

        //如果传入的productIds不为空，则伤处指定的订单项
        if(productIds !=null && !productIds.isEmpty()){

            /*在未删除前从OrederItem中获取所要删除的订单项，更新仓库*/
            //获取所删除的订单项
            List<StandardItem> deleteItems = orderItemDao.ItemDetial(orderId,productIds);
            // 判断订单项是否为空
            if (deleteItems != null && !deleteItems.isEmpty()) {
                for (StandardItem deleteitem : deleteItems) {
                  productDao.repiyStock(deleteitem.getProductId(),deleteitem.getQuantity());
                }
            } else {
                // 如果没有订单项，可以选择设置默认价格或进行其他操作
                System.out.print("该订单项不存在不用更新库存！");
            }

            //删除指定的订单项
            orderItemDao.deleteItem(orderId,productIds);


            /*更新订单的总价格*/
            //获取已删除后的所剩的订单项
            List<StandardItem> items = orderItemDao.queryByOrderId(orderId);
            BigDecimal totalPrice = BigDecimal.ZERO;

            // 判断订单项是否为空
            if (items != null && !items.isEmpty()) {
                for (StandardItem item : items) {
                    totalPrice = totalPrice.add(item.calculatePrice());  // 累加每个商品的价格
                }
            } else {
                // 如果没有订单项，可以选择设置默认价格或进行其他操作
                totalPrice = BigDecimal.ZERO;  // 设置为零，或者你可以抛出异常等
            }
            // 设置总价格
            order.setTotalPrice(totalPrice);
            Date date = new Date();
            LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            order.setUpdatedAt(localDate);
            ordermDao.updateOrderA(order);
            return true;

        }
        //如果没有指定删除的订单项product_id，则就删除整个订单
        //先把订单项整个给删完
        orderItemDao.deleteOrderItem(orderId);
        //再删除订单
        ordermDao.deleteOrder(orderId);
        return true;
    }

    //根据买家ID查询已支付订单
    public List<Map<String,Object>> getPaidOrders(Integer buyerId,String status) {
        //查询已支付的订单
        List<StandardOrder> orders=ordermDao.getPaidOrders(buyerId,status);
        List<Map<String,Object>> result=new ArrayList<>();
        for(StandardOrder order:orders){
            Map<String,Object> orderMap=new HashMap<>();
            orderMap.put("orderId",order.getOrderId());
            orderMap.put("orderStatus", order.getOrderStatus());
            orderMap.put("totalPrice", order.getTotalPrice());
            orderMap.put("buyerId", order.getBuyerId());
            orderMap.put("createdAt", order.getCreatedAt());
            orderMap.put("updatedAt", order.getUpdatedAt());

            //查询相关订单项
            List<StandardItem> items=orderItemDao.queryByOrderId(order.getOrderId());
            List<Map<String,Object>> itemlist=new ArrayList<>();
            for(StandardItem item:items){
                Map<String,Object> itemMap=new HashMap<>();
                itemMap.put("productId", item.getProductId());
                itemMap.put("quantity", item.getQuantity());
                itemMap.put("itemstatus",item.getDisplayStatus());
                //获取订单项中的商品信息
                Product product= productDao.queryById(item.getProductId());
                if(product!=null){
                    itemMap.put("productName", product.getName());
                    itemMap.put("productPrice", product.getPrice());
                    itemMap.put("imagePath", product.getImagePath());
                    itemMap.put("category", product.getCategory());
                }
                itemlist.add(itemMap);
            }
            orderMap.put("items", itemlist);
            result.add(orderMap);
        }
        return result;
    }

  /*  public List<Map<String,Object>> getAllPaidOrders() {
        List<StandardOrder> orders = ordermDao.getAllPaidOrders();  // 去掉 buyerId 限制
        List<Map<String,Object>> itemlist = new ArrayList<>();
        for (StandardOrder order : orders) {
            List<StandardItem> items = orderItemDao.queryByOrderId(order.getOrderId());

            for (StandardItem item : items) {
                Map<String,Object> itemMap = new HashMap<>();
                itemMap.put("id", item.getOrderItemsId());
                itemMap.put("buyerId",order.getBuyerId());
                itemMap.put("createdAt", order.getCreatedAt());
                itemMap.put("updatedAt", order.getUpdatedAt());
                itemMap.put("productId", item.getProductId());
                itemMap.put("quantity", item.getQuantity());
                String buyerName = buyerMapper.selectUsernameById(order.getBuyerId());
                itemMap.put("buyerName", buyerName);



                Product product = productDao.queryById(item.getProductId());
                if (product != null) {
                    itemMap.put("productName", product.getName());
                    itemMap.put("productPrice", product.getPrice());
                    itemMap.put("imagePath", product.getImagePath());
                    itemMap.put("category", product.getCategory());

                    BigDecimal quantity = BigDecimal.valueOf(item.getQuantity()); // quantity 是整数
                    BigDecimal productPrice = BigDecimal.valueOf(product.getPrice()); // 由 double 转 BigDecimal，避免精度丢失
                    BigDecimal totalPrice = productPrice.multiply(quantity);
                    itemMap.put("totalPrice", totalPrice);
                }
                itemMap.put("confirmation", item.getConfirmation());
                itemMap.put("stockup", item.getStockUp());
                itemMap.put("sendorder", item.getSendOrder());
                itemMap.put("completion", item.getCompletion());

                itemlist.add(itemMap);
            }

        }

        return itemlist;
    }
*/
   public List<OrderItemDTO> getPaidOrdersByPage(int pageNum, int pageSize) {
      int offset = (pageNum - 1) * pageSize;
      return orderItemDTOMapper.getPaidOrderItems(offset, pageSize);

   }

    public int countTotalPaidOrders() {
        return orderItemDTOMapper.countPaidOrderItems();
    }

}
